from datetime import datetime
import psutil
import socket
from postgresql_db import *


def check_process_exist_by_name(name):
    for item in psutil.process_iter():
        if item.name() == name:
            return item


def detect_process(name, db_rule):
    process = check_process_exist_by_name(name)
    if process:
        process_info = process.as_dict(attrs=['create_time', 'status', 'name', 'pid'])
        process_info['fqdn'] = socket.getfqdn()
        process_info['process_name'] = process_info.pop('name')
        process_info['state'] = process_info.pop('status')
        process_info['start_time'] = process_info.pop('create_time')
        process_info['start_time'] = datetime.fromtimestamp(process_info['start_time']).strftime(
            '%Y-%m-%d %H:%M:%S.%f')[:-3]
    else:
        process_info = {'pid': None, 'process_name': name, 'state': psutil.STATUS_STOPPED, 'start_time': None,
                        'fqdn': None}
    insert(process_info, db_rule['table_name'], db_rule['columns'])
